<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="标题" prop="title">
        <el-input class="w500" v-model="form.title" placeholder="商品标题"></el-input>
      </el-form-item>
      <el-form-item label="商品分类">
        <el-cascader clearable v-model="cateIds" :options="tree" :props="defaultProps" :show-all-levels="false"></el-cascader>
      </el-form-item>
      <el-form-item label="积分">
        <el-input class="w100" v-model="form.integral" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="总数量">
        <el-input class="w100" v-model="form.origin_number" placeholder="例：1"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input class="w500" v-model="form.desc" type="textarea" autosize placeholder="请输入描述内容"></el-input>
      </el-form-item>
      <el-form-item label="商品图片">
        <el-upload
          :action="upload_url"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-success="picUploadSuccess"
          :on-remove="picRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <div style="color: #666666;">允许上传多张商品图片,默认值第一张为商品封面图片</div>
        <el-dialog v-model="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="排序" prop="order">
        <el-input class="w100" v-model="form.order" type="number"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('form')">提交</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import notify from '@/tools/notify'
  import { UPLOAD_URL } from '@/config/const'

  export default {
    data: function () {
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        form: {
          cate_id: '',
          title: '',
          integral: '',
          profile_pic: '',
          imgs_urls: '',
          imgs_ids: '',
          origin_number: '',
          desc: '',
          order: 1
        },
        cateIds: [],
        defaultProps: {
          value: 'id',
          label: 'name',
          children: '_child'
        },
        rules: {
          title: [
            {required: true, message: '请输入商品标题', trigger: 'blur'}
          ],
          desc: [
            {required: true, message: '请输入描述', trigger: 'blur'}
          ]
        }
      }
    },
    computed: {
      ...mapState({
        tree: state => state.mallgoodsclass.tree,
        pic: state => state.mallgoods.pic
      }),
      upload_url () {
        return UPLOAD_URL
      }
    },
    async created () {
      await this.goodsClassTree()
      delete this.pic.id
      delete this.pic.path
      delete this.pic.profile_pic
    },
    methods: {
      // 获取商品分类树
      async goodsClassTree () {
        let payload = {
          id: 0
        }
        await this.$store.dispatch('mallgoodsclass/goodsClassTree', payload)
      },
      onSubmit (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (Number(this.cateIds.length) > 0) {
              this.form.cate_id = this.cateIds[Number(this.cateIds.length) - 1]
            } else {
              this.form.cate_id = 0
            }
            this.form.imgs_urls = this.pic.path
            this.form.imgs_ids = this.pic.id
            this.form.profile_pic = this.pic.profile_pic
            this.$store.dispatch('mallgoods/addIntegralGoods', this.form).then(res => {
              notify.success(res.msg)
              this.$router.push('/integral/goods')
            })
          }
        })
      },
      picUploadSuccess (file, response, fileList) {
        const self = this
        const pic = {}
        if (file.code !== 200) {
          fileList.pop()
          notify.warning('商品图片上传失败')
        } else {
          if (fileList.length > 6) {
            let diff = fileList.length - 6
            fileList.splice(6, diff)
            notify.warning('商品图片最多上传6张')
          } else {
            if (JSON.stringify(self.pic) === '{}') {
              pic.id = file.res.id
              pic.path = 'http://' + file.res.save_path + '/' + file.res.filename
            } else {
              pic.id = self.pic.id + ',' + file.res.id
              pic.path = self.pic.path + ',' + 'http://' + file.res.save_path + '/' + file.res.filename
            }
            pic.profile_pic = pic.path.split(',')[0]
            self.$store.commit('mallgoods/MALLPICDATA', pic)
            notify.success('商品图片上传成功')
          }
        }
      },
      picRemove (file, fileList) {
        const self = this
        const picList = {}
        for (let i = 0; i < fileList.length; i++) {
          if (JSON.stringify(picList) === '{}') {
            picList.id = fileList[i].response.res.id
            picList.path = 'http://' + fileList[i].response.res.save_path + '/' + fileList[i].response.res.filename
          } else {
            picList.id = picList.id + ',' + fileList[i].response.res.id
            picList.path = picList.path + ',' + 'http://' + fileList[i].response.res.save_path + '/' + fileList[i].response.res.filename
          }
        }
        picList.profile_pic = picList.path.split(',')[0]
        self.$store.commit('mallgoods/MALLPICDATA', picList)
      },
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      goBack () {
        this.$router.go(-1)
      }
    }
  }
</script>

<style scoped>
  .ml-15 {
    margin-left: 15px;
    margin-bottom: 30px;
  }
  .input-style {
    margin-right: 15px;
    background-color: #fff;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #bfcbd9;
    box-sizing: border-box;
    color: #1f2d3d;
    font-size: inherit;
    width: 500px;
    height: 36px;
    line-height: 1;
    outline: 0;
    padding: 3px 10px;
  }
</style>
